package com.ash.socketb.dual.length;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 客户端连接方式
 * 1. 客户端可以使用telnet工具进行连接
 * 2. 自己写socket客户端连接
 */
public class ServerDualDemo {

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8081);

        do {
            Socket oneConnect = serverSocket.accept();
            System.out.println("有客户来了:" + oneConnect);

            handleConnect(oneConnect);

        } while (true);

    }

    /**
     * 可以使用异步处理，这里主要是演示功能，不做异步处理方式。简化案例复杂度
     *
     * @param accept
     * @throws IOException
     */
    private static void handleConnect(Socket accept) {
        try (InputStream inputStream = accept.getInputStream();
             OutputStream outputStream = accept.getOutputStream()
        ) {

            StringBuilder requestPayload = new StringBuilder();
            while (true) {
                int first = inputStream.read();
                if (first == -1) {
                    System.out.println("关闭流了");
                    break;
                }

                int second = inputStream.read();

                int len = (first << 8) + second;
                byte[] buff = new byte[len];
                int read = inputStream.read(buff);

                // 获取请求内容
                String requestBody = new String(buff, 0, read, StandardCharsets.UTF_8);


                // 处理请求
                System.out.println(requestBody);

                // 响应
                String responseText = "success";
                outputStream.write(responseText.length() >> 8);
                outputStream.write(responseText.length());
                outputStream.write(responseText.getBytes(StandardCharsets.UTF_8));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
